# coding=utf-8
import os
from flask import Flask, render_template, request, session, redirect
from src.router.router import register

app = Flask(__name__, static_folder="static", template_folder="templates")
# 必须设置
app.secret_key = os.urandom(24)
# 注册api
register(app)


@app.before_request
def before_request():
    request_path = request.path
    if request_path != "/login" and not request_path.startswith("/static"):
        # 如果是请求的登录页面
        username = session.get("username")
        if username is None:
            return redirect("/login")
    elif request_path == "/login":
        username = session.get("username")
        if username is not None:
            return redirect("/")


@app.route("/")
def index():
    return render_template("index.html")


@app.route("/login", methods=["GET", "POST"])
def login_page():
    if request.method.lower() == "get":
        return render_template("login.html")
    user = request.form.get("username", None)
    pwd = request.form.get("password", None)
    if user is None or pwd is None:
        return redirect("/login")
    if user == "admin" and pwd == "123456":
        session["username"] = user
        return {
            "code": 200,
            "msg": "登录成功"
        }
    return {
        "code": 500,
        "msg": "用户名或密码错误"
    }


def main():
    app.run(host="127.0.0.1", port=8080, debug=True)


if __name__ == '__main__':
    main()
